import {
  ui
} from "../../../tools/ui";
import {
  ds
} from "../../../tools/data"

import {
  pages
} from '../../../tools/pages'

Page({
  data: {
    action: 'select',
    errMsg: "",
    totalPage: 1,
    page: 1,
    pageSize: 12,
  },
  async init() {
    const {
      pageSize
    } = this.data
    const res = await ds.coll('goods')
      .where(this.makeCondition())
      .count()

    const totalPage = Math.ceil(res.total / pageSize)
    this.setData({
      totalPage
    })
    this.loadGoods()
  },
  loadGoods() {
    const {
      page,
      pageSize,
    } = this.data

    ds.coll('goods')
      .where(this.makeCondition())
      .orderBy("top", "desc")
      .orderBy("ticket.gift", "desc")
      .orderBy("fastDelivery", "desc")
      .orderBy("promotion", "desc")
      .orderBy("visible", "desc")
      .orderBy("updateTime", "desc")
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
      .then(res => {
        this.setData({
          list: res.data
        })
      })
  },
  makeCondition() {
    const {
      ticket,
      visible
    } = this.data
    const _ = ds.cmd

    return {
      ticket: ticket ? {
        gift: _.exists(true)
      } : undefined,
      visible: (() => {
        if (visible == undefined) return undefined
        return visible ? _.or([_.eq(true), _.eq("true"), _.exists(false)]) : _.or(_.eq(false), _.eq("false"))
      })()
    }
  },
  onPageChange(e) {
    const {
      page
    } = e.detail
    this.setData({
      page
    })
    this.loadGoods()
  },
  addGoods(e) {
    wx.navigateTo({
      url: '../goodsEdit/index',
    })
  },
  onGoodsCancelTap() {
    pages.back(prePage => {
      prePage.goodsSelected(null)
    })
  },

  goodsClick(e) {
    if (this.data.action == 'edit') {
      wx.navigateTo({
        url: '../goodsEdit/index?action=edit&id=' + e.currentTarget.dataset.id,
      })
    } else {
      ui.confirmx('确定选择吗？').then(res => {
        if (!res) return
        pages.back(prePage => {
          const goods = e.currentTarget.dataset, // {id, title}
            option = this.data.option
          prePage.goodsSelected(goods, option)
        })
      })
    }

  },
  onLoad(option) {
    const {
      action, // select, edit
      ticket,
      visible
    } = option

    this.setData({
      option,
      ticket,
      action: option.action || 'select', // select
      visible: ds.checkTrue(visible)
    })

    wx.setNavigationBarTitle({
      title: action == 'select' ? '选择商品' : '商品列表',
    })
    this.init();
  },
});